import style from "./index.module.css";
import { Avatar, Button, Form, Input, message, Modal } from "antd";
import { CameraOutlined, UserOutlined, EditOutlined } from "@ant-design/icons";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { uploadApi } from "@/apis/upload";
import { useEffect, useRef, useState } from "react";
import { getUserInfoApi, updateUserInfoApi } from "@/apis/user";
import {
  clearToken,
  setProfile,
  clearProfile,
} from "@/store/modules/userStore";
import { logoutApi, confirmPasswordApi } from "@/apis/user";
import router from "@/router";

export default function UserInfo() {
  const profile = useSelector((state: any) => state.user.profile);
  const dispatch = useDispatch();

  const fileInputRef = useRef<HTMLInputElement>(null);

  const [userInfoForm, setUserInfoForm] = useState({
    id: null,
    account: null,
    username: null,
    avatar: null,
    email: null,
    telephone: null,
  });

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isCahngePasswordModalVisible, setIsCahngePasswordModalVisible] =
    useState(false);
  const [isShowConfirmPassword, setIsShowConfirmPassword] = useState(false);

  const [oldPassword, setOldPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmNewPassword, setConfirmNewPassword] = useState("");

  // 提取重复的列表项渲染逻辑
  const renderListItems = (count: number) => {
    return Array(count)
      .fill(0)
      .map((_, index) => (
        <li key={index}>
          <Link to="/" className={style.listItem}>
            菜单项 {index + 1}
          </Link>
        </li>
      ));
  };

  // 提取重复的表单项渲染逻辑
  const renderFormItems = () => {
    if (!profile) return null;

    // 定义要显示的字段及其对应的中文标签
    const fieldLabels = {
      account: "账户",
      username: "用户名",
      email: "邮箱",
      telephone: "手机号",
    };

    return Object.entries(profile)
      .filter(([key]) => key in fieldLabels) // 只显示有对应标签的字段
      .map(([key, value]) => (
        <label key={key} className={style.formLabel}>
          <section className={style.label}>
            <h3 className={style.labelTitle}>
              {fieldLabels[key as keyof typeof fieldLabels]}
            </h3>
            <span className={style.labelValue}>
              {(value as string) || "无"}
            </span>
            {key !== "createTime" && key !== "updateTime" && (
              <EditOutlined
                className={style.editIcon}
                onClick={() => setIsModalVisible(true)}
              />
            )}
          </section>
        </label>
      ));
  };

  async function changeAvatar(e: any) {
    const file = e.target.files?.[0];
    const formData = new FormData();
    formData.append("file", file);
    if (file) {
      try {
        const res: any = await uploadApi(formData);
        setUserInfoForm({ ...userInfoForm, avatar: res.data });
      } catch (error) {}
    }
    if (e.target) e.target.value = "";
  }

  async function handleSubmit() {
    // 这里处理确认修改的逻辑
    console.log("提交修改", userInfoForm);
    const form = { ...userInfoForm, id: profile.id };
    try {
      if (await confirmPassword()) {
        const res: any = await updateUserInfoApi(form);
        if (res.code === 0) {
          message.success("修改成功");
          setIsModalVisible(false);
          const res: any = await getUserInfoApi();
          if (res.code === 0) {
            setIsShowConfirmPassword(false);
            setOldPassword("");
            dispatch(setProfile(res.data));
          }
        } else {
          message.error("修改失败");
        }
      } else {
        message.error("密码错误");
      }
    } catch (error) {
      message.error("修改失败");
    }
  }

  function handleCancel() {
    message.info("取消修改");
    setIsModalVisible(false);
    setUserInfoForm({ ...profile });
  }

  async function confirmPassword() {
    const formData = new FormData();
    formData.append("password", oldPassword);
    try {
      const res: any = await confirmPasswordApi(formData);
      if (res.code === 0) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      message.error("请求失败");
      return false;
    }
  }

  async function handleCahngePassword() {
    if (!oldPassword || !newPassword || !confirmNewPassword) {
      let value;
      let mag = `请输入${value}密码`;
      if (!oldPassword) {
        value = "旧";
      } else if (!newPassword) {
        value = "新";
      } else if (!confirmNewPassword) {
        value = "确认";
      }
      message.error(mag);
      return;
    }

    if (newPassword !== confirmNewPassword) {
      message.error("两次输入的密码不一致");
      return;
    }

    if (newPassword === oldPassword) {
      message.error("新密码不能与旧密码相同");
      return;
    }

    try {
      const res: any = await confirmPassword();
      if (res) {
        const form = {
          ...userInfoForm,
          password: newPassword,
          id: profile.id,
        };
        const res: any = await updateUserInfoApi(form);
        if (res.code === 0) {
          message.success("密码修改成功");
          setIsCahngePasswordModalVisible(false);
          setOldPassword("");
          setNewPassword("");
          setConfirmNewPassword("");
          await logoutApi();
          dispatch(clearToken(), clearProfile());
          router.navigate("/");
        } else {
          message.error("密码修改失败");
        }
      } else {
        message.error("原密码错误");
      }
    } catch (error) {
      message.error("请求失败");
    }
  }

  useEffect(() => {
    setUserInfoForm({ ...profile });
  }, []);

  return (
    <div className={style.userInfoContainer}>
      <h3 className={style.sectionTitle}>个人信息</h3>
      <section className={style.mainLayout}>
        {/* 左侧信息卡片 */}
        <aside className={style.sidebar}>
          <section className={style.profileCard}>
            <label htmlFor="avatar-upload" className={style.avatarContainer}>
              <div className={style.avatarWrapper}>
                <Avatar
                  size={200}
                  className={style.avatarImage}
                  src={userInfoForm?.avatar}
                  icon={<UserOutlined />}
                  onError={() => {
                    return true;
                  }}
                />
                <div className={style.avatarOverlay}>
                  <CameraOutlined className={style.cameraIcon} />
                  <span className={style.uploadText}>更换头像</span>
                </div>
              </div>
              <input
                id="avatar-upload"
                type="file"
                ref={fileInputRef}
                onChange={changeAvatar}
                className={style.hiddenInput}
                accept="image/*"
              />
            </label>
            <h2 className={style.username}>
              {userInfoForm?.username || "访客用户"}
            </h2>
          </section>

          <section className={style.menuCard}>
            <nav>
              <ul className={style.menuList}>
                {renderListItems(5)} {/* 减少菜单项数量 */}
              </ul>
            </nav>
          </section>
        </aside>

        {/* 右侧内容区域 */}
        <main className={style.contentArea}>
          <form className={style.profileForm}>{renderFormItems()}</form>
          <section className={style.instructions}>
            <span>注册时间: {profile?.createTime}</span>
            <span style={{ marginLeft: "1rem" }}>
              更新时间: {profile?.updateTime}
            </span>
          </section>
        </main>
      </section>
      <section
        style={{ width: "100%", display: "flex", justifyContent: "flex-end" }}
      >
        <Button
          type="primary"
          style={{ marginTop: "1em", marginLeft: "auto !important" }}
          className={style.submitButton}
          onClick={() => setIsCahngePasswordModalVisible(true)}
        >
          修改密码
        </Button>
      </section>
      <Modal
        title="编辑个人信息"
        zIndex={1024}
        open={isModalVisible}
        onCancel={handleCancel}
        onOk={() => {
          setIsShowConfirmPassword(true);
        }}
        cancelText="取消修改"
        okText="确认修改"
        destroyOnClose
      >
        <Form
          layout="vertical"
          initialValues={userInfoForm}
          onFinish={() => {
            setIsShowConfirmPassword(true);
          }}
        >
          <Form.Item
            label="账户"
            name="account"
            // rules={[{ required: true, message: "请输入账户!" }]}
          >
            <Input
              value={userInfoForm.account || ""}
              onChange={(e: any) =>
                setUserInfoForm({
                  ...userInfoForm,
                  account: e.target.value,
                })
              }
            />
          </Form.Item>

          <Form.Item
            label="用户名"
            name="username"
            // rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input
              value={userInfoForm.username || ""}
              onChange={(e: any) =>
                setUserInfoForm({
                  ...userInfoForm,
                  username: e.target.value,
                })
              }
            />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            // rules={[
            //   { required: true, message: "请输入邮箱!" },
            //   { type: "email", message: "请输入有效的邮箱!" },
            // ]}
          >
            <Input
              value={userInfoForm.email || ""}
              onChange={(e: any) =>
                setUserInfoForm({
                  ...userInfoForm,
                  email: e.target.value,
                })
              }
            />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="telephone"
            // rules={[{ required: true, message: "请输入手机号!" }]}
          >
            <Input
              value={userInfoForm.telephone || ""}
              onChange={(e: any) =>
                setUserInfoForm({
                  ...userInfoForm,
                  telephone: e.target.value,
                })
              }
            />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="修改密码"
        zIndex={1024}
        open={isCahngePasswordModalVisible}
        onCancel={() => setIsCahngePasswordModalVisible(false)}
        onOk={handleCahngePassword}
        cancelText="取消修改"
        okText="确认修改"
        destroyOnClose
      >
        <Form
          labelAlign="right"
          layout="vertical"
          onFinish={handleCahngePassword}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: "请输入旧密码!" }]}
          >
            <Input.Password
              value={oldPassword}
              onChange={(e) => setOldPassword(e.target.value)}
            />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: "请输入新密码!" }]}
          >
            <Input.Password
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[{ required: true, message: "请确认新密码!" }]}
          >
            <Input.Password
              value={confirmNewPassword}
              onChange={(e) => setConfirmNewPassword(e.target.value)}
            />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="确认密码"
        zIndex={1024}
        open={isShowConfirmPassword}
        onCancel={() => {
          setOldPassword("");
          setIsShowConfirmPassword(false);
        }}
        onOk={handleSubmit}
        cancelText="取消"
        okText="确认"
        destroyOnClose
      >
        <Form labelAlign="right" layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            label="请输入密码"
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password
              value={oldPassword}
              onChange={(e) => setOldPassword(e.target.value)}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
